package com.authentications.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName JWTUtils
 * @Author xiezhuocai
 * @Description jwt加减密类(filter方式在用)
 * @Date 2021/12/15 14:29
 */
public class JWTUtils {

    //秘钥 可以改成配置文件配置
    private static final String secret ="asdfasdf";

    private static final String jwtId = "tokenId";

    public static String createToken(String subject) {
        String token =
                Jwts.builder().setExpiration(new Date(System.currentTimeMillis() +1000 *60*60*24)).setSubject(subject).setId(jwtId).signWith(SignatureAlgorithm.HS256,generalKey()).compact();
        return token;
    }


    public static String parseToken(String token) {
        Claims body = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        String subject = body.getSubject();
        return subject;
    }

    /**
     * 由字符串生成加密key
     * @return
     */
    public static SecretKey generalKey() {
        String stringKey = secret;
        byte[] encodedKey = Base64.decodeBase64(stringKey);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    //用来测试的
    public static void main(String[] args) {

        try {

            String name ="{\"id\":\"1\",\"name\":\"关云长\"}";

            String token =createToken(name);

            System.out.println("token:" + token);

            TimeUnit.SECONDS.sleep(4);

            String srcStr =parseToken(token);

            System.out.println("解析出来：" + srcStr);

        }catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

}

